package com.eobard.executor;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.eobard.config.obfuscate.ObfuscatorConfig;
import com.eobard.enums.RunningEnum;
import com.eobard.obfuscate.IObfuscator;
import com.eobard.utils.AndroidRFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @Author: Eobard Gu
 * @Date: 2025-08-04
 * @Description: 混淆统一执行器, 将所有配置过的混淆核心类注入, 过滤非空混淆类后初始化并调用混淆
 */
@Component
public class ObfuscationExecutor {

    @Value("${obfuscate.ext.source.path:temp/source}")
    private String sourceExt;

    @Autowired
    private List<IObfuscator> obfuscators;

    public void obfuscate(ObfuscatorConfig config) {
        //如果没设置源码路径,默认设置源码路径
        if (StrUtil.isBlank(config.getSourceExt())) {
            config.setSourceExt(sourceExt);
        }
        //如果是安卓项目则添加R文件
        if (config.getRunningStatus() == RunningEnum.ANDROID_PROjECT) {
            String packageName = AndroidRFileUtils.getPackageName(config.getSourceRoot());
            if (null != packageName) {
                String rFileContent = AndroidRFileUtils.getRFileContent(config.getSourceRoot(), packageName);
                if (null != rFileContent) {
//                    Path packagePath = Paths.get(config.getSourceExt(), packageName.replace(".", "/"));
//                    if (!packagePath.toFile().exists()) {
//                        packagePath.toFile().mkdirs();
//                    }

                    String resourcesPath = Paths.get(System.getProperty("user.dir"), "src", "main", "resources").toString();
                    // 生成最终 packagePath
                    Path packagePath = Paths.get(resourcesPath, sourceExt, packageName.replace(".", "/"));
                    // 最终 R.java 文件路径
                    Path rFilePath = packagePath.resolve("R.java");
                    // 确保目录存在
                    try {
                        Files.createDirectories(packagePath);
                        // 如果文件存在就删除
                        if (Files.exists(rFilePath)) {
                            Files.delete(rFilePath);
                        }
                        FileUtil.writeUtf8String(rFileContent, rFilePath.toFile());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        //获取执行器的所有混淆器,遍历开始执行混淆
        obfuscators.stream()
                .filter(obf -> obf.supports(config))
                .forEach(item -> {
                    item.initialize(config);//初始化数据
                    item.obfuscate(config);//混淆
                });
    }
}
